package project

import (
	"context"
	"encoding/json"
	"fmt"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/constants"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/common/utils"
	opptyStatusRepo "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/business_opportunity/oppty_status"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/bigdata_remote"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/infrastructure/repository/remote/opensearch_remote"
	pb "git.mycaigou.com/gfyx/micro-gfyx-oppty-service/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/business_opportunity/oppty_status"
	"git.mycaigou.com/gfyx/micro-gfyx-oppty-service/service/common/option"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"sort"
	"strings"
)

type projectService struct {
	openSearchRepos    opensearch_remote.OpenSearchRepositoryIface
	opptyStatusRepos   opptyStatusRepo.GfyxOpptyStatusReposIface
	bigDataServiceRepo bigdata_remote.BigDataServiceRepositoryIface
	opptyStatusService oppty_status.OpptyStatusServiceIface
	optionService      option.OptionServiceIface
}

func NewProjectService(
	openSearchRepos opensearch_remote.OpenSearchRepositoryIface,
	opptyStatusRepos opptyStatusRepo.GfyxOpptyStatusReposIface,
	bigDataServiceRepo bigdata_remote.BigDataServiceRepositoryIface,
	opptyStatusService oppty_status.OpptyStatusServiceIface,
	optionService option.OptionServiceIface,
) ProjectServiceIface {
	return &projectService{
		openSearchRepos:    openSearchRepos,
		opptyStatusRepos:   opptyStatusRepos,
		bigDataServiceRepo: bigDataServiceRepo,
		opptyStatusService: opptyStatusService,
		optionService:      optionService,
	}
}

func (s *projectService) SearchProject(ctx context.Context, request *pb.SearchProjectRequest) (*pb.SearchProjectResponse, error) {
	//如果需要带股权过滤
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.GetProjectListRequest{
		Page:                   request.Page,
		PageSize:               request.PageSize,
		Keyword:                request.Keyword,
		OrganizingCode:         strings.Join(organizingCodeArr, ","),
		CompanyAreaCode:        strings.Join(request.CompanyAreaCode, ","),
		LandUsage:              strings.Join(request.LandUsage, ","),
		ProjectType:            strings.Join(request.ProjectType, ","),
		FitmentFee:             strings.Join(request.FitmentFee, ","),
		CompanyType:            strings.Join(request.CompanyType, ","),
		CompanyLabel:           strings.Join(request.CompanyLabel, ","),
		IndustryCategory:       strings.Join(request.IndustryCategory, ","),
		ProjectPriceGtAvgLabel: strings.Join(request.ProjectPriceGtAvgLabel, ","),
		TakeLandDateStart:      request.TakeLandDateStart,
		TakeLandDateEnd:        request.TakeLandDateEnd,
		ProjectDateStart:       request.ProjectDateStart,
		ProjectDateEnd:         request.ProjectDateEnd,
		BuildingDateStart:      request.BuildingDateStart,
		BuildingDateEnd:        request.BuildingDateEnd,
		OpenDateStart:          request.OpenDateStart,
		OpenDateEnd:            request.OpenDateEnd,
		CompletedDateStart:     request.CompletedDateStart,
		CompletedDateEnd:       request.CompletedDateEnd,
	}
	//区域
	request.AreaCode, _ = s.filterAreaCode(ctx, request.AreaCode)
	openSearchRequest.AreaCode = strings.Join(request.AreaCode, ",")

	projectListResponse, err := s.openSearchRepos.GetProjectList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "opensearch GetProjectList,err:%s", err.Error())
	}
	result := &pb.SearchProjectResponse{}
	if projectListResponse == nil {
		return result, nil
	}

	idList := make([]string, 0)
	for _, item := range projectListResponse.List {
		idList = append(idList, item.ID)
		data := &pb.ProjectData{
			Id:                       item.ID,
			ProjectStageLatest:       item.ProjectStageLatest,
			CompanyType:              item.CompanyType,
			DeveloperName:            item.DeveloperName,
			OrganizingCode:           item.OrganizingCode,
			TopCompanyName:           item.TopCompanyName,
			TopCompanyOrganizingCode: item.TopCompanyOrganizingCode,
			CompanyProvince:          item.CompanyProvince,
			CompanyProvinceCode:      item.CompanyProvinceCode,
			CompanyCity:              item.CompanyCity,
			CompanyCityCode:          item.CompanyCityCode,
			Province:                 item.Province,
			ProvinceCode:             item.ProvinceCode,
			City:                     item.City,
			CityCode:                 item.CityCode,
			Title:                    item.Title,
			PriceGtAvgLabel:          item.PriceGtAvgLabel,
			Address:                  item.Address,
			IndustryCategoryBig:      item.IndustryCategoryBig,
			IndustryCategoryMiddle:   item.IndustryCategoryMiddle,
			IndustryCategorySmall:    item.IndustryCategorySmall,
			OrderDate:                item.OrderDate,
			ContactCnt:               item.PurchaseContactCnt + item.CoopSupplierContactCnt,
			BiddingInfoCnt:           item.BiddingInfoCnt,
			ApprovalInfoCnt:          item.ApprovalInfoCnt,
			OpeningInfoCnt:           item.OpeningInfoCnt,
			LandInfoCnt:              item.LandInfoCnt,
			BuildingInfoCnt:          item.BuildingInfoCnt,
			CompletionInfoCnt:        item.CompletionInfoCnt,
			ProjectBaseInfoCnt:       item.ProjectBaseInfoCnt,
			LandTitle_HL:             item.LandTitleHL,
			BuildTitle_HL:            item.BuildTitleHL,
			OpeningTitle_HL:          item.OpeningTitleHL,
			Title_HL:                 item.TitleHL,
			DeveloperName_HL:         item.DeveloperNameHL,
			XScore:                   item.Score,
			ProjectPriceGtAvgLabel:   item.ProjectPriceGtAvgLabel,
		}
		if data.ProjectStageLatest != "" {
			data.ProjectStageLatest += "阶段"
		}
		if data.ProjectPriceGtAvgLabel == "非高端项目" { //非高端项目，不展示
			data.ProjectPriceGtAvgLabel = ""
		}
		//拿地用途
		landUsageArr := make([]string, 0)
		for _, v := range item.LandUsageLabelArr {
			landUsageArr = append(landUsageArr, v.Label)
		}
		data.LandUsageLabelArr = strings.Join(landUsageArr, ",")
		//工程用途
		projectTypeArr := make([]string, 0)
		for _, v := range item.ProjectTypeLabelArr {
			projectTypeArr = append(projectTypeArr, v.Label)
		}
		data.ProjectTypeLabelArr = strings.Join(projectTypeArr, ",")
		//装修类型
		fitmentFeeArr := make([]string, 0)
		for _, v := range item.FitmentFeeLabelArr {
			fitmentFeeArr = append(fitmentFeeArr, v.Label)
		}
		data.FitmentFeeLabelArr = strings.Join(fitmentFeeArr, ",")
		//企业标签
		companyLabelArr := make([]string, 0)
		for _, v := range item.CompanyLabelArr {
			companyLabelArr = append(companyLabelArr, v.Label)
		}
		data.CompanyLabelArr = strings.Join(companyLabelArr, ",")
		//商机状态
		data.OpptyStatus = ""
		//招标
		for _, v := range item.BiddingInfoArr {
			if v.PublishDate != "" && len(v.PublishDate) >= 10 {
				v.PublishDate = v.PublishDate[0:10]
			}
			data.BiddingInfoArr = append(data.BiddingInfoArr, &pb.BiddingInfo{
				Id:          v.Id,
				Title:       v.Title,
				PublishDate: v.PublishDate,
				Type:        "新" + v.Type,
			})
		}
		//轨道图节点
		data.NodeList = s.getNodeList(ctx, item)
		if data.OrderDate != "" && len(data.OrderDate) >= 10 {
			data.OrderDate = data.OrderDate[0:10]
		}
		result.List = append(result.List, data)
	}

	//商机状态
	getOpptyStatusBatchRequest := &pb.GetOpptyStatusBatchRequest{
		DataSource:   constants.OpptySourceProjectCycle,
		DataSourceId: idList,
	}
	opptyStatus, err := s.opptyStatusService.GetOpptyStatusBatch(ctx, getOpptyStatusBatchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOpptyStatusBatch接口异常:%s,错误信息:%s", err)
	}
	for _, item := range result.List {
		for _, opptyValue := range opptyStatus {
			if item.Id != "" && item.Id == opptyValue.DataSourceId {
				item.OpptyStatus = opptyValue.StatusName
			}
		}
	}

	result.Total = projectListResponse.Total
	return result, nil
}
func (s *projectService) filterAreaCode(ctx context.Context, areaCodeList []string) ([]string, error) {
	newAreaCodeList := make([]string, 0)
	defaultAreaCode, err := s.optionService.GetRadarAreaOption(ctx)
	if err != nil {
		stark.Logger.Infof(ctx, "GetRadarAreaOption err:%s", err.Error())
		return newAreaCodeList, err
	}
	if defaultAreaCode != nil {
		if len(areaCodeList) == 0 {
			for _, v := range defaultAreaCode.Options {
				newAreaCodeList = append(newAreaCodeList, v.AreaCode)
			}
			// todo 因为业务需求调整，暂时不需要过滤，通过权限和权益接口进行控制
			//if len(newAreaCodeList) == 0 { //如果权益没有一个省份：传递-1，即列表不返回任何数据
			//	newAreaCodeList = append(newAreaCodeList, "-1")
			//}
		} else {
			for _, pv := range areaCodeList {
				for _, qv := range defaultAreaCode.Options {
					if pv == qv.AreaCode {
						newAreaCodeList = append(newAreaCodeList, qv.AreaCode)
					}
				}
			}
		}
	}
	return newAreaCodeList, nil
}
func (s *projectService) getNodeList(ctx context.Context, data *opensearch_remote.GetProjectListItem) []*pb.NodeData {
	res := make([]*pb.NodeData, 0)
	//拿地
	landNode := &pb.NodeData{
		NodeName: constants.ProjectNodeLand,
		NodeCnt:  data.LandInfoCnt,
		Status:   s.getNodeStatus(ctx, constants.ProjectNodeLand, data.ProjectStageLatest),
	}

	landInfoDate := make([]string, 0)
	for _, v := range data.LandInfoArr {
		landInfoDate = append(landInfoDate, v.TakeLandDate)
	}
	lessLand := func(i, j int) bool {
		return landInfoDate[i] > landInfoDate[j]
	}
	sort.Slice(landInfoDate, lessLand) //排序：倒叙
	for _, v := range landInfoDate {
		if v != "" && len(v) >= 10 {
			v = v[0:10]
		}
		landNode.DataList = append(landNode.DataList, &pb.NodeTimeList{
			Time: v,
		})
		if len(landNode.DataList) >= 5 {
			landNode.DataList = landNode.DataList[0:5]
		}
	}
	if len(landNode.DataList) > 0 {
		landNode.NodeDate = utils.GetDateOnly(landInfoDate[0]) //当前节点时间取最近时间
	}
	res = append(res, landNode)
	//立项
	approvalNode := &pb.NodeData{
		NodeName: constants.ProjectNodeApprove,
		NodeCnt:  data.ApprovalInfoCnt,
		Status:   s.getNodeStatus(ctx, constants.ProjectNodeApprove, data.ProjectStageLatest),
	}
	approveInfoDate := make([]string, 0)
	for _, v := range data.ApprovalInfoArr {
		approveInfoDate = append(approveInfoDate, v.ProjectDate)
	}
	lessApprove := func(i, j int) bool {
		return approveInfoDate[i] > approveInfoDate[j]
	}
	sort.Slice(approveInfoDate, lessApprove) //排序：倒叙
	for _, v := range approveInfoDate {
		if v != "" && len(v) >= 10 {
			v = v[0:10]
		}
		approvalNode.DataList = append(approvalNode.DataList, &pb.NodeTimeList{
			Time: v,
		})
		if len(approvalNode.DataList) >= 5 {
			approvalNode.DataList = approvalNode.DataList[0:5]
		}
	}
	if len(approveInfoDate) > 0 {
		approvalNode.NodeDate = utils.GetDateOnly(approveInfoDate[0]) //当前节点时间取最近时间
	}
	res = append(res, approvalNode)
	//开工
	buildingNode := &pb.NodeData{
		NodeName: constants.ProjectNodeBuild,
		NodeCnt:  data.BuildingInfoCnt,
		Status:   s.getNodeStatus(ctx, constants.ProjectNodeBuild, data.ProjectStageLatest),
	}
	buildInfoDate := make([]string, 0)
	for _, v := range data.BuildingInfoArr {
		buildInfoDate = append(buildInfoDate, v.BuildingDate)
	}
	lessBuild := func(i, j int) bool {
		return buildInfoDate[i] > buildInfoDate[j]
	}
	sort.Slice(buildInfoDate, lessBuild) //排序：倒叙
	for _, v := range buildInfoDate {
		if v != "" && len(v) >= 10 {
			v = v[0:10]
		}
		buildingNode.DataList = append(buildingNode.DataList, &pb.NodeTimeList{
			Time: v,
		})
		if len(buildingNode.DataList) >= 5 {
			buildingNode.DataList = buildingNode.DataList[0:5]
		}
	}
	if len(buildInfoDate) > 0 {
		buildingNode.NodeDate = utils.GetDateOnly(buildInfoDate[0]) //当前节点时间取最近时间
	}
	res = append(res, buildingNode)
	//开盘
	openNode := &pb.NodeData{
		NodeName: constants.ProjectNodeOpen,
		NodeCnt:  data.OpeningInfoCnt,
		Status:   s.getNodeStatus(ctx, constants.ProjectNodeOpen, data.ProjectStageLatest),
	}
	openInfoDate := make([]string, 0)
	for _, v := range data.OpeningInfoArr {
		openInfoDate = append(openInfoDate, v.OpeningDate)
	}
	lessOpen := func(i, j int) bool {
		return openInfoDate[i] > openInfoDate[j]
	}
	sort.Slice(openInfoDate, lessOpen) //排序：倒叙
	for _, v := range openInfoDate {
		if v != "" && len(v) >= 10 {
			v = v[0:10]
		}
		openNode.DataList = append(openNode.DataList, &pb.NodeTimeList{
			Time: v,
		})
		if len(openNode.DataList) >= 5 {
			openNode.DataList = openNode.DataList[0:5]
		}
	}
	if len(openInfoDate) > 0 {
		openNode.NodeDate = utils.GetDateOnly(openInfoDate[0]) //当前节点时间取最近时间
	}

	res = append(res, openNode)
	//竣工
	completeNode := &pb.NodeData{
		NodeName: constants.ProjectNodeComplete,
		NodeCnt:  data.CompletionInfoCnt,
		Status:   s.getNodeStatus(ctx, constants.ProjectNodeComplete, data.ProjectStageLatest),
	}
	completeInfoDate := make([]string, 0)
	for _, v := range data.CompletionInfoArr {
		completeInfoDate = append(completeInfoDate, v.CompletedDate)
	}
	lessComplete := func(i, j int) bool {
		return completeInfoDate[i] > completeInfoDate[j]
	}
	sort.Slice(completeInfoDate, lessComplete) //排序：倒叙
	for _, v := range completeInfoDate {
		if v != "" && len(v) >= 10 {
			v = v[0:10]
		}
		completeNode.DataList = append(completeNode.DataList, &pb.NodeTimeList{
			Time: v,
		})
		if len(completeNode.DataList) >= 5 {
			completeNode.DataList = completeNode.DataList[0:5]
		}
	}
	if len(completeInfoDate) > 0 {
		completeNode.NodeDate = utils.GetDateOnly(completeInfoDate[0]) //当前节点时间取最近时间
	}
	res = append(res, completeNode)

	return res
}

func (s *projectService) getNodeStatus(ctx context.Context, targetNode string, currentNode string) int32 {
	nodeList := make([]string, 0)
	nodeList = append(nodeList, constants.ProjectNodeLand)
	nodeList = append(nodeList, constants.ProjectNodeApprove)
	nodeList = append(nodeList, constants.ProjectNodeBuild)
	nodeList = append(nodeList, constants.ProjectNodeOpen)
	nodeList = append(nodeList, constants.ProjectNodeComplete)
	currentNodeK := 0
	targetNodeK := 0
	for k, v := range nodeList {
		if v == currentNode {
			currentNodeK = k
		}
		if v == targetNode {
			targetNodeK = k
		}
	}

	if targetNodeK < currentNodeK {
		return 1 //已完成
	} else if targetNodeK == currentNodeK {
		return 2 //进行中
	} else {
		return 3 //未开始
	}
}
func (s *projectService) FuzzySearchProject(ctx context.Context, request *pb.FuzzySearchProjectRequest) (*pb.FuzzySearchProjectResponse, error) {
	openSearchRequest := &opensearch_remote.FuzzySearchProjectRequest{
		Keyword: request.Keyword,
	}
	fuzzyProjectResponse, err := s.openSearchRepos.FuzzySearchProject(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "opensearch FuzzySearchProject,err:%s", err.Error())
	}
	result := &pb.FuzzySearchProjectResponse{}
	if fuzzyProjectResponse == nil {
		return result, nil
	}

	for _, item := range fuzzyProjectResponse {
		data := &pb.FuzzySearchProjectItem{
			TitleHL: item.TitleHL,
			Title:   item.Title,
		}
		result.List = append(result.List, data)
	}
	return result, nil
}
func (s *projectService) ProjectDetail(ctx context.Context, request *pb.ProjectDetailRequest) (*pb.ProjectDetailResponse, error) {
	bigDataRequest := &bigdata_remote.GetProjectListRequest{
		Id:       request.Id,
		PageSize: 1,
		PageNum:  1,
	}
	getProjectListResponse, err := s.bigDataServiceRepo.GetProjectList(ctx, bigDataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetProjectList,err:%s", err.Error())
	}
	resp := &pb.ProjectDetailResponse{}
	if getProjectListResponse != nil && getProjectListResponse.Total > 0 {
		item := getProjectListResponse.List[0]
		resp.Data = &pb.ProjectData{
			Id:                       item.ID,
			ProjectStageLatest:       item.ProjectStageLatest,
			CompanyType:              item.CompanyType,
			DeveloperName:            item.DeveloperName,
			OrganizingCode:           item.OrganizingCode,
			TopCompanyName:           item.TopCompanyName,
			TopCompanyOrganizingCode: item.TopCompanyOrganizingCode,
			CompanyProvince:          item.CompanyProvince,
			CompanyProvinceCode:      item.CompanyProvinceCode,
			CompanyCity:              item.CompanyCity,
			CompanyCityCode:          item.CompanyCityCode,
			Province:                 item.Province,
			ProvinceCode:             item.ProvinceCode,
			City:                     item.City,
			CityCode:                 item.CityCode,
			Title:                    item.Title,
			PriceGtAvgLabel:          item.PriceGtAvgLabel,
			Address:                  item.Address,
			IndustryCategoryBig:      item.IndustryCategoryBig,
			IndustryCategoryMiddle:   item.IndustryCategoryMiddle,
			IndustryCategorySmall:    item.IndustryCategorySmall,
			OrderDate:                item.OrderDate,
			ContactCnt:               item.PurchaseContactCnt + item.CoopSupplierContactCnt,
			LandInfoCnt:              item.LandInfoCnt,
			ApprovalInfoCnt:          item.ApprovalInfoCnt,
			BuildingInfoCnt:          item.BuildingInfoCnt,
			OpeningInfoCnt:           item.OpeningInfoCnt,
			CompletionInfoCnt:        item.CompletionInfoCnt,
			BiddingInfoCnt:           item.BiddingInfoCnt,
			ProjectBaseInfoCnt:       item.ProjectBaseInfoCnt,
		}
		if resp.Data.ProjectStageLatest != "" {
			resp.Data.ProjectStageLatest += "阶段"
		}
		//轨道图
		NodeData := &opensearch_remote.GetProjectListItem{}
		NodeData.ProjectStageLatest = item.ProjectStageLatest
		if item.LandUsageLabelArr != "" {
			err = json.Unmarshal([]byte(item.LandInfoArr), &NodeData.LandInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		NodeData.LandInfoCnt = item.LandInfoCnt
		if item.ApprovalInfoArr != "" {
			err = json.Unmarshal([]byte(item.ApprovalInfoArr), &NodeData.ApprovalInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		NodeData.ApprovalInfoCnt = item.ApprovalInfoCnt
		if item.BuildingInfoArr != "" {
			err = json.Unmarshal([]byte(item.BuildingInfoArr), &NodeData.BuildingInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		NodeData.BuildingInfoCnt = item.BuildingInfoCnt
		if item.OpeningInfoArr != "" {
			err = json.Unmarshal([]byte(item.OpeningInfoArr), &NodeData.OpeningInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		NodeData.OpeningInfoCnt = item.OpeningInfoCnt
		if item.CompletionInfoArr != "" {
			err = json.Unmarshal([]byte(item.CompletionInfoArr), &NodeData.CompletionInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		NodeData.CompletionInfoCnt = item.CompletionInfoCnt
		if item.BiddingInfoArr != "" {
			err = json.Unmarshal([]byte(item.BiddingInfoArr), &NodeData.BiddingInfoArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
		}
		resp.Data.NodeList = s.getNodeList(ctx, NodeData)
		//招标
		for _, v := range NodeData.BiddingInfoArr {
			resp.Data.BiddingInfoArr = append(resp.Data.BiddingInfoArr, &pb.BiddingInfo{
				Id:          v.Id,
				PublishDate: v.PublishDate,
				Title:       v.Title,
				Type:        "新" + v.Type,
			})
		}
		//拿地用途
		if item.LandUsageLabelArr != "" {
			landUsage := make([]string, 0)
			err = json.Unmarshal([]byte(item.LandUsageLabelArr), &NodeData.LandUsageLabelArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
			for _, p := range NodeData.LandUsageLabelArr {
				landUsage = append(landUsage, p.Label)
			}
			resp.Data.LandUsageLabelArr = strings.Join(landUsage, ",")
		}
		//工程用途
		if item.ProjectTypeLabelArr != "" {
			projectType := make([]string, 0)
			err = json.Unmarshal([]byte(item.ProjectTypeLabelArr), &NodeData.ProjectTypeLabelArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
			for _, p := range NodeData.ProjectTypeLabelArr {
				projectType = append(projectType, p.Label)
			}
			resp.Data.ProjectTypeLabelArr = strings.Join(projectType, ",")
		}
		//装修类型
		if item.FitmentFeeLabelArr != "" {
			fitmentFee := make([]string, 0)
			err = json.Unmarshal([]byte(item.FitmentFeeLabelArr), &NodeData.FitmentFeeLabelArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
			for _, p := range NodeData.FitmentFeeLabelArr {
				fitmentFee = append(fitmentFee, p.Label)
			}
			resp.Data.FitmentFeeLabelArr = strings.Join(fitmentFee, ",")
		}
		//企业标签
		if item.CompanyLabelArr != "" {
			companyLabel := make([]string, 0)
			err = json.Unmarshal([]byte(item.CompanyLabelArr), &NodeData.CompanyLabelArr)
			if err != nil {
				stark.Logger.Errorf(ctx, "json Unmarshal ,err:%s", err.Error())
			}
			for _, p := range NodeData.CompanyLabelArr {
				companyLabel = append(companyLabel, p.Label)
			}
			resp.Data.CompanyLabelArr = strings.Join(companyLabel, ",")
		}

		//商机状态
		GetOpptyStatusRequest := &pb.GetOpptyStatusRequest{
			DataSourceId: item.ID,
			DataSource:   constants.OpptySourceProjectCycle,
			DetailPage:   true,
		}
		opptyStatus, err := s.opptyStatusService.GetOpptyStatus(ctx, GetOpptyStatusRequest)
		if err != nil {
			stark.Logger.Errorf(ctx, "获取商机状态GetOpptyStatus,err:%s", err.Error())
		}
		if opptyStatus != nil {
			resp.Data.OpptyStatus = opptyStatus.StatusName
		}

	}

	return resp, nil
}

func (s *projectService) ProjectDetailLand(ctx context.Context, request *pb.ProjectDetailLandRequest) (*pb.ProjectDetailLandResponse, error) {
	bigdataRequest := &bigdata_remote.ProjectDetailLandRequest{
		PageNum:   request.Page,
		PageSize:  request.PageSize,
		ProjectId: request.ProjectId,
	}

	landResponse, err := s.bigDataServiceRepo.ProjectDetailLand(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata ProjectDetailLand,err:%s", err.Error())
	}
	result := &pb.ProjectDetailLandResponse{}
	if landResponse == nil {
		return result, nil
	}

	for _, item := range landResponse.List {
		data := &pb.ProjectDetailLandData{
			Id:             item.Id,
			DeveloperName:  item.DeveloperName,
			OrganizingCode: item.OrganizingCode,
			Province:       item.Province,
			ProvinceCode:   item.ProvinceCode,
			City:           item.City,
			CityCode:       item.CityCode,
			InfoType:       item.InfoType,
			IsPriceGtAvg:   item.IsPriceGtAvg,
			LandAddress:    item.LandAddress,
			LandTitle:      item.LandTitle,
			LandUsage:      item.LandUsage,
			TakeLandDate:   item.TakeLandDate,
		}
		//小数点处理
		allArea, _ := utils.Decimal(item.AllArea, "2")
		data.AllArea = allArea

		landUnitPrice, _ := utils.Decimal(item.LandUnitPrice, "2")
		data.LandUnitPrice = landUnitPrice

		takeLandPrice, _ := utils.Decimal(item.TakeLandPrice, "2")
		data.TakeLandPrice = takeLandPrice
		//时间处理
		if data.TakeLandDate != "" && len(data.TakeLandDate) >= 10 {
			data.TakeLandDate = data.TakeLandDate[0:10]
		}
		if item.PriceGtAvgLabel == "高端项目客群" {
			data.PriceGtAvgLabel = "高端项目"
		}

		result.List = append(result.List, data)
	}
	result.Total = landResponse.Total
	return result, nil
}

func (s *projectService) ProjectDetailBuild(ctx context.Context, request *pb.ProjectDetailBuildRequest) (*pb.ProjectDetailBuildResponse, error) {
	bigdataRequest := &bigdata_remote.ProjectDetailBuildRequest{
		PageNum:   request.Page,
		PageSize:  request.PageSize,
		ProjectId: request.ProjectId,
	}

	buildResponse, err := s.bigDataServiceRepo.ProjectDetailBuild(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata ProjectDetailBuild,err:%s", err.Error())
	}
	result := &pb.ProjectDetailBuildResponse{}
	if buildResponse == nil {
		return result, nil
	}

	for _, item := range buildResponse.List {
		data := &pb.ProjectDetailBuildData{
			Id:             item.Id,
			DeveloperName:  item.DeveloperName,
			OrganizingCode: item.OrganizingCode,
			Province:       item.Province,
			ProvinceCode:   item.ProvinceCode,
			City:           item.City,
			CityCode:       item.CityCode,
			AllArea:        item.AllArea,
			CompletedTime:  item.CompletedTime,
			StartTime:      item.StartTime,
			ConscorpName:   item.ConscorpName,
			Address:        item.Address,
			PrjName:        item.PrjName,
			PrjPropertyNum: item.PrjPropertyNum,
			PrjTypeNum:     item.PrjTypeNum,
			ContractPrice:  item.ContractPrice,
		}
		//小数点处理
		allArea, _ := utils.DecimalFloat(item.AllArea)
		data.AllArea = allArea

		contractPrice, _ := utils.DecimalFloat(item.ContractPrice)
		data.ContractPrice = contractPrice
		//时间处理
		if data.CompletedTime != "" && len(data.CompletedTime) >= 10 {
			data.CompletedTime = data.CompletedTime[0:10]
		}
		if data.StartTime != "" && len(data.StartTime) >= 10 {
			data.StartTime = data.StartTime[0:10]
		}
		if item.PriceGtAvgLabel == "高端项目客群" {
			data.PriceGtAvgLabel = "高端项目"
		}

		result.List = append(result.List, data)
	}
	result.Total = buildResponse.Total
	return result, nil
}

func (s *projectService) ProjectDetailSale(ctx context.Context, request *pb.ProjectDetailSaleRequest) (*pb.ProjectDetailSaleResponse, error) {
	bigdataRequest := &bigdata_remote.ProjectDetailSaleRequest{
		PageNum:   request.Page,
		PageSize:  request.PageSize,
		ProjectId: request.ProjectId,
	}

	saleResponse, err := s.bigDataServiceRepo.ProjectDetailSale(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata ProjectDetailSale,err:%s", err.Error())
	}
	result := &pb.ProjectDetailSaleResponse{}
	if saleResponse == nil {
		return result, nil
	}

	for _, item := range saleResponse.List {
		data := &pb.ProjectDetailSaleData{
			Id:                item.Id,
			DeveloperName:     item.DeveloperName,
			OrganizingCode:    item.OrganizingCode,
			Province:          item.Province,
			ProvinceCode:      item.ProvinceCode,
			City:              item.City,
			CityCode:          item.CityCode,
			Region:            item.Region,
			OpeningTime:       item.OpeningTime,
			DeliveryTime:      item.DeliveryTime,
			FitmentFee:        item.FitmentFee,
			Address:           item.Address,
			ProjectTitle:      item.ProjectTitle,
			SellStatus:        item.SellStatus,
			NewHouseDealMoney: item.NewHouseDealMoney,
			NewHouseDealNum:   item.NewHouseDealNum,
			NewHouseOnNum:     item.NewHouseOnNum,
			NewHouseSaleRate:  item.NewHouseSaleRate,
		}
		//小数点处理
		buildArea, _ := utils.Decimal(item.BuildArea, "2")
		data.BuildArea = buildArea

		newHouseDealMoney, _ := utils.DecimalFloat(data.NewHouseDealMoney)
		data.NewHouseDealMoney = newHouseDealMoney
		newHouseSaleRate, _ := utils.DecimalFloat(data.NewHouseSaleRate)
		data.NewHouseSaleRate = newHouseSaleRate

		//时间处理
		if data.OpeningTime != "" && len(data.OpeningTime) >= 10 {
			data.OpeningTime = data.OpeningTime[0:10]
		}
		if data.DeliveryTime != "" && len(data.DeliveryTime) >= 10 {
			data.DeliveryTime = data.DeliveryTime[0:10]
		}
		if item.PriceGtAvgLabel == "高端项目客群" {
			data.PriceGtAvgLabel = "高端项目"
		}

		result.List = append(result.List, data)
	}
	result.Total = saleResponse.Total
	return result, nil
}

func (s *projectService) ProjectDetailBid(ctx context.Context, request *pb.ProjectDetailBidRequest) (*pb.ProjectDetailBidResponse, error) {
	bigdataRequest := &bigdata_remote.ProjectDetailBidRequest{
		PageNum:   request.Page,
		PageSize:  request.PageSize,
		ProjectId: request.ProjectId,
	}

	bidResponse, err := s.bigDataServiceRepo.ProjectDetailBid(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata ProjectDetailBid,err:%s", err.Error())
	}
	result := &pb.ProjectDetailBidResponse{}
	if bidResponse == nil {
		return result, nil
	}

	for _, item := range bidResponse.List {
		data := &pb.ProjectDetailBidData{
			Id:                                 item.Id,
			DeveloperName:                      item.DeveloperName,
			OrganizingCode:                     item.OrganizingCode,
			Province:                           item.Province,
			City:                               item.City,
			Title:                              item.Title,
			PublishTime:                        item.PublishTime,
			DataSource:                         item.DataSource,
			Type:                               item.Type,
			FirstWinbidSupplierName:            item.FirstWinbidSupplierName,
			FirstWinbidSupplierOrganizingCode:  item.FirstWinbidSupplierOrganizingCode,
			SecondWinbidSupplierName:           item.SecondWinbidSupplierName,
			SecondWinbidSupplierOrganizingCode: item.SecondWinbidSupplierOrganizingCode,
			ThirdWinbidSupplierName:            item.ThirdWinbidSupplierName,
			ThirdWinbidSupplierOrganizingCode:  item.ThirdWinbidSupplierOrganizingCode,
		}

		//时间处理
		if data.PublishTime != "" && len(data.PublishTime) >= 10 {
			data.PublishTime = data.PublishTime[0:10]
		}
		//省市
		if data.Province != "" {
			provinceArr := strings.Split(data.Province, ",")
			if len(provinceArr) > 0 {
				data.Province = provinceArr[0]
			}
		}
		if data.City != "" {
			cityArr := strings.Split(data.City, ",")
			if len(cityArr) > 0 {
				data.City = cityArr[0]
			}
		}

		result.List = append(result.List, data)
	}
	result.Total = bidResponse.Total
	return result, nil
}

func (s *projectService) TakenLandDetail(ctx context.Context, request *pb.TakenLandDetailRequest) (*pb.TakenLandDetailResponse, error) {
	bigdataRequest := &bigdata_remote.TakenLandListRequest{
		PageNum:  1,
		PageSize: 1,
		Id:       request.Id,
	}
	takeLandResponse, err := s.bigDataServiceRepo.TakenLandList(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata TakenLandList,err:%s", err.Error())
		return nil, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "获取详情异常,id:"+request.Id)
	}
	resp := &pb.TakenLandDetailResponse{}
	if takeLandResponse != nil && len(takeLandResponse.List) > 0 {
		resp.Id = takeLandResponse.List[0].Id
		allArea, _ := utils.Decimal(takeLandResponse.List[0].AllArea, "2")
		resp.AllArea = allArea
		resp.Authority = takeLandResponse.List[0].Authority
		resp.BuildEndPlan = takeLandResponse.List[0].BuildEndPlan
		resp.BuildStartPlan = takeLandResponse.List[0].BuildStartPlan
		capablitity, _ := utils.Decimal(takeLandResponse.List[0].Capablitity, "2")
		resp.Capablitity = capablitity
		resp.City = takeLandResponse.List[0].City
		resp.CityCode = takeLandResponse.List[0].CityCode
		resp.DeliverDate = strings.Split(takeLandResponse.List[0].DeliverDate, " ")[0]
		resp.DeveloperName = takeLandResponse.List[0].DeveloperName
		resp.EnterpriseNature = takeLandResponse.List[0].EnterpriseNature
		resp.Industry = takeLandResponse.List[0].Industry
		resp.InfoType = takeLandResponse.List[0].InfoType
		resp.IsPriceGtAvg = takeLandResponse.List[0].IsPriceGtAvg
		resp.IsTopCompanyContainDeveloper = takeLandResponse.List[0].IsTopCompanyContainDeveloper
		resp.IssueDate = strings.Split(takeLandResponse.List[0].IssueDate, " ")[0]
		resp.LandAddress = takeLandResponse.List[0].LandAddress
		resp.LandLevel = takeLandResponse.List[0].LandLevel
		resp.LandSource = takeLandResponse.List[0].LandSource
		resp.LandTitle = takeLandResponse.List[0].LandTitle
		landUnitPrice, _ := utils.Decimal(takeLandResponse.List[0].LandUnitPrice, "2")
		resp.LandUnitPrice = landUnitPrice
		landUnitPriceAvg, _ := utils.Decimal(takeLandResponse.List[0].LandUnitPriceAvg, "2")
		resp.LandUnitPriceAvg = landUnitPriceAvg
		resp.LandUsage = takeLandResponse.List[0].LandUsage
		resp.Lat = takeLandResponse.List[0].Lat
		resp.Lng = takeLandResponse.List[0].Lng
		resp.OrganizingCode = takeLandResponse.List[0].OrganizingCode
		plannedArea, _ := utils.Decimal(takeLandResponse.List[0].PlannedArea, "2")
		resp.PlannedArea = plannedArea
		resp.ProjectName = takeLandResponse.List[0].ProjectName
		resp.Province = takeLandResponse.List[0].Province
		resp.ProvinceCode = takeLandResponse.List[0].ProvinceCode
		resp.Region = takeLandResponse.List[0].Region
		resp.SourceUpdateTime = strings.Split(takeLandResponse.List[0].SourceUpdateTime, " ")[0]
		resp.TakeLandDate = strings.Split(takeLandResponse.List[0].TakeLandDate, " ")[0]
		takeLandPrice, _ := utils.Decimal(takeLandResponse.List[0].TakeLandPrice, "2")
		resp.TakeLandPrice = takeLandPrice
		resp.TopCompanyType = takeLandResponse.List[0].TopCompanyType
		resp.TopDeveloperName = takeLandResponse.List[0].TopDeveloperName
		resp.TopOrganizingCode = takeLandResponse.List[0].TopOrganizingCode
		resp.TopParentCompanyType = takeLandResponse.List[0].TopParentCompanyType
		resp.TradeType = takeLandResponse.List[0].TradeType
		resp.UseTimeDescription = takeLandResponse.List[0].UseTimeDescription
		//关联公司:拿地企业、顶级企业
		resp.RelatedCompany = make([]*pb.ProjectRelatedCompany, 0)
		if takeLandResponse.List[0].DeveloperName != "" {
			Labels := make([]string, 0)
			if takeLandResponse.List[0].CompanyTypeLabel != "" {
				Labels = append(Labels, takeLandResponse.List[0].CompanyTypeLabel)
			}
			resp.RelatedCompany = append(resp.RelatedCompany, &pb.ProjectRelatedCompany{
				CompanyName:       takeLandResponse.List[0].DeveloperName,
				OrganizingCode:    takeLandResponse.List[0].OrganizingCode,
				Role:              constants.RelatedCompanyTypeLandCompany,
				Labels:            Labels,
				TopOrganizingCode: takeLandResponse.List[0].TopOrganizingCode,
				TopCompanyName:    takeLandResponse.List[0].TopDeveloperName,
			})
		}
		//oppty_status字段
		opptyStatusRequest := &pb.GetOpptyStatusRequest{
			DataSource:   constants.OpptySourceLand,
			DataSourceId: request.Id,
			DetailPage:   true,
		}
		opptyStatus, err := s.opptyStatusService.GetOpptyStatus(ctx, opptyStatusRequest)
		if err != nil {
			stark.Logger.Errorf(ctx, "GetOpptyStatus,err:%s", err.Error())
		}
		resp.OpptyStatus = opptyStatus.StatusName

	} else {
		return nil, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "拿地详情不存在,id:"+request.Id)
	}
	return resp, nil
}

func (s *projectService) SaleList(ctx context.Context, request *pb.SaleListRequest) (*pb.SaleListResponse, error) {
	var newIsPriceGtAvg []string
	for _, v := range request.IsPriceGtAvg {
		if v == "高端项目" {
			v = "是"
		} else {
			v = "否"
		}
		newIsPriceGtAvg = append(newIsPriceGtAvg, v)
	}
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	bigdataRequest := &opensearch_remote.SaleListRequest{
		PageSize:              request.PageSize,
		Page:                  request.Page,
		Keyword:               request.Keyword,
		CompanyArea:           strings.Join(request.CompanyArea, ","),
		CompanyType:           strings.Join(request.CompanyType, ","),
		IsPriceGtAvg:          strings.Join(newIsPriceGtAvg, ","),
		FitmentFeeLabel:       strings.Join(request.FitmentFeeLabel, ","),
		PropertyCategoryLabel: strings.Join(request.PropertyCategoryLabel, ","),
		Area:                  strings.Join(request.Area, ","),
		OpeningTimeStart:      request.OpeningTimeStart,
		OpeningTimeEnd:        request.OpeningTimeEnd,
		DeliveryTimeStart:     request.DeliveryTimeStart,
		DeliveryTimeEnd:       request.DeliveryTimeEnd,
		OrganizingCode:        strings.Join(organizingCodeArr, ","),
	}
	for _, v := range request.CompanyLabel {
		if v == constants.CompanyLabelDeveloperTop100Label {
			bigdataRequest.DeveloperTop100Label = v
		} else if v == constants.CompanyLabelNewDecorateExpandLabel {
			bigdataRequest.NewDecorateExpandLabel = v
		} else if v == constants.CompanyLabelNewLandUsageExpandLabel {
			bigdataRequest.NewLandUsageExpandLabel = v
		} else if v == constants.CompanyLabelNewAreaExpandLabel {
			bigdataRequest.NewAreaExpandLabel = v
		} else if v == constants.CompanyLabelPriceGtAvgLabel {
			bigdataRequest.PriceGtAvgLabel = v
		} else if v == constants.CompanyLabelUrbanInvestmentLabel {
			bigdataRequest.UrbanInvestmentLabel = v
		}
	}
	saleResponse, err := s.openSearchRepos.SaleList(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "opensearch SaleList,err:%s", err.Error())
	}
	resp := &pb.SaleListResponse{
		List: make([]*pb.SaleListData, 0),
	}

	resp.Total = saleResponse.Total
	for _, item := range saleResponse.List {
		row := &pb.SaleListData{}
		row.Id = item.Id
		row.Address = item.Address
		row.City = item.City
		row.CityCode = item.CityCode
		row.DeliveryTime = strings.Split(item.DeliveryTime, " ")[0]
		row.DeveloperName = item.DeveloperName
		row.FitmentFee = item.FitmentFeeLabel
		row.IsPriceGtAvg = item.IsPriceGtAvg
		if row.IsPriceGtAvg == "是" {
			row.IsPriceGtAvg = "高端项目"
		} else {
			row.IsPriceGtAvg = ""
		}
		row.NewHouseDealNum = item.NewHouseDealNum
		row.NewHouseOnNum = item.NewHouseOnNum

		newHouseDealMoney, _ := utils.DecimalFloat(item.NewHouseDealMoney)
		row.NewHouseDealMoney = newHouseDealMoney
		newHouseSaleRate, _ := utils.DecimalFloat(item.NewHouseSaleRate)
		row.NewHouseSaleRate = newHouseSaleRate

		row.OpeningTime = strings.Split(item.OpeningTime, " ")[0]
		row.OrganizingCode = item.OrganizingCode
		row.ProjectTitle = item.ProjectTitle
		row.Province = item.Province
		row.ProvinceCode = item.ProvinceCode
		row.DeveloperName_HL = item.DeveloperNameHL
		row.ProjectTitle_HL = item.ProjectTitleHL
		row.SellStatus = item.SellStatus

		resp.List = append(resp.List, row)
	}

	return resp, nil
}

func (s *projectService) SaleDetail(ctx context.Context, request *pb.SaleDetailRequest) (*pb.SaleDetailResponse, error) {
	bigdataRequest := &bigdata_remote.SaleListRequest{
		PageNum:  1,
		PageSize: 1,
		Id:       request.Id,
	}

	saleResponse, err := s.bigDataServiceRepo.SaleList(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata SaleList,err:%s", err.Error())
	}
	resp := &pb.SaleDetailResponse{}
	if saleResponse != nil && saleResponse.Total > 0 {
		resp.Id = saleResponse.List[0].Id
		resp.Address = saleResponse.List[0].Address
		resp.ArchitecturalStyle = saleResponse.List[0].ArchitecturalStyle
		buildArea, _ := utils.Decimal(saleResponse.List[0].BuildArea, "2")
		resp.BuildArea = buildArea
		resp.BuildingNum = saleResponse.List[0].BuildingNum
		resp.Characteristic = saleResponse.List[0].Characteristic
		resp.City = saleResponse.List[0].City
		resp.CityCode = saleResponse.List[0].CityCode
		coveredArea, _ := utils.Decimal(saleResponse.List[0].CoveredArea, "2")
		resp.CoveredArea = coveredArea
		resp.DeliveryTime = strings.Split(saleResponse.List[0].DeliveryTime, " ")[0]
		resp.DeveloperName = saleResponse.List[0].DeveloperName
		resp.EnterpriseNature = saleResponse.List[0].EnterpriseNature
		resp.FitmentFee = saleResponse.List[0].FitmentFee
		resp.Decorate = saleResponse.List[0].Decorate
		resp.Households = saleResponse.List[0].Households
		resp.IsPriceGtAvg = saleResponse.List[0].IsPriceGtAvg
		resp.IsTopCompanyContainDeveloper = saleResponse.List[0].IsTopCompanyContainDeveloper
		resp.LandDate = saleResponse.List[0].LandDate
		resp.Lat = saleResponse.List[0].Lat
		resp.Lng = saleResponse.List[0].Lng
		resp.Level = saleResponse.List[0].Level
		maxArea, _ := utils.Decimal(saleResponse.List[0].MaxArea, "2")
		resp.MaxArea = maxArea
		minArea, _ := utils.Decimal(saleResponse.List[0].MinArea, "2")
		resp.MinArea = minArea
		resp.NewHouseDealNum = saleResponse.List[0].NewHouseDealNum
		resp.NewHouseOnNum = saleResponse.List[0].NewHouseOnNum
		newHouseDealMoney, _ := utils.DecimalFloat(saleResponse.List[0].NewHouseDealMoney)
		resp.NewHouseDealMoney = newHouseDealMoney
		newHouseSaleRate, _ := utils.DecimalFloat(saleResponse.List[0].NewHouseSaleRate)
		resp.NewHouseSaleRate = newHouseSaleRate
		resp.OpeningTime = strings.Split(saleResponse.List[0].OpeningTime, " ")[0]
		resp.OrganizingCode = saleResponse.List[0].OrganizingCode
		resp.PresellNum = saleResponse.List[0].PresellNum
		resp.Price = saleResponse.List[0].Price
		priceCityAvg, err := utils.Decimal(saleResponse.List[0].PriceCityAvg, "2")
		resp.PriceCityAvg = priceCityAvg
		resp.ProjectTitle = saleResponse.List[0].ProjectTitle
		resp.PropertyCategory = saleResponse.List[0].PropertyCategory
		resp.PropertyCompany = saleResponse.List[0].PropertyCompany
		resp.Province = saleResponse.List[0].Province
		resp.ProvinceCode = saleResponse.List[0].ProvinceCode
		resp.Region = saleResponse.List[0].Region
		resp.SellStatus = saleResponse.List[0].SellStatus
		resp.TopCompanyType = saleResponse.List[0].TopCompanyType
		resp.TopDeveloperName = saleResponse.List[0].TopDeveloperName
		resp.TopOrganizingCode = saleResponse.List[0].TopOrganizingCode
		resp.TopParentCompanyType = saleResponse.List[0].TopParentCompanyType
		//关联公司:开发商、顶级企业
		resp.RelatedCompany = make([]*pb.ProjectRelatedCompany, 0)
		if saleResponse.List[0].DeveloperName != "" {
			Labels := make([]string, 0)
			if saleResponse.List[0].CompanyTypeLabel != "" {
				Labels = append(Labels, saleResponse.List[0].CompanyTypeLabel)
			}
			resp.RelatedCompany = append(resp.RelatedCompany, &pb.ProjectRelatedCompany{
				CompanyName:       saleResponse.List[0].DeveloperName,
				OrganizingCode:    saleResponse.List[0].OrganizingCode,
				Role:              constants.RelatedCompanyTypeKfs,
				Labels:            Labels,
				TopOrganizingCode: saleResponse.List[0].TopOrganizingCode,
				TopCompanyName:    saleResponse.List[0].TopDeveloperName,
			})
		}
		//oppty_status字段
		opptyStatusRequest := &pb.GetOpptyStatusRequest{
			DataSource:   constants.OpptySourceSale,
			DataSourceId: request.Id,
			DetailPage:   true,
		}
		opptyStatus, err := s.opptyStatusService.GetOpptyStatus(ctx, opptyStatusRequest)
		if err != nil {
			stark.Logger.Errorf(ctx, "GetOpptyStatus,err:%s", err.Error())
		}
		resp.OpptyStatus = opptyStatus.StatusName

	} else {
		return nil, ykerrcode.TogRPCError(ykerrcode.INVALID_PARAMS, "开盘详情不存在,id:"+request.Id)
	}
	return resp, nil
}

func (s *projectService) NewHouse(ctx context.Context, request *pb.NewHouseRequest) (*pb.NewHouseResponse, error) {
	bigdataRequest := &bigdata_remote.NewHouseRequest{
		OrganizingCode: request.OrganizingCode,
		PresellNum:     request.PresellNum,
		PageNum:        request.Page,
		PageSize:       request.PageSize,
	}

	newHouseResponse, err := s.bigDataServiceRepo.NewHouse(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata NewHouse,err:%s", err.Error())
	}
	resp := &pb.NewHouseResponse{
		List: make([]*pb.NewHouseData, 0),
	}
	if newHouseResponse != nil && newHouseResponse.Total > 0 {
		for _, v := range newHouseResponse.List {
			row := &pb.NewHouseData{}
			buildArea, _ := utils.DecimalFloat(v.BuildArea)
			row.BuildArea = buildArea
			row.BuildFloor = v.BuildFloor
			row.BuildName = v.BuildName
			row.CityName = v.CityName
			row.Developer = v.Developer
			innerArea, _ := utils.DecimalFloat(v.InnerArea)
			row.InnerArea = innerArea
			row.MasterId = v.MasterId
			row.OrganizingCode = v.OrganizingCode
			row.PresellNum = v.PresellNum
			row.ProjectAddress = v.ProjectAddress
			row.ProjectTitle = v.ProjectTitle
			row.RegionName = v.RegionName
			row.RoomName = v.RoomName
			row.RoomState = v.RoomState
			row.RoomUse = v.RoomUse
			row.SupplierDate = v.SupplierDate
			row.TradeDate = v.TradeDate
			resp.List = append(resp.List, row)
		}
		resp.Total = newHouseResponse.Total
	}
	return resp, nil
}

func (s *projectService) GetTopProject(ctx context.Context, request *pb.GetTopProjectRequest) (*pb.GetTopProjectResponse, error) {
	bigdataRequest := &bigdata_remote.GetTopProjectRequest{
		PageNum:  request.Page,
		PageSize: request.PageSize,
		Id:       request.Id,
	}
	getTopProjectResponse, err := s.bigDataServiceRepo.GetTopProject(ctx, bigdataRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "bigdata GetTopProject,err:%s", err.Error())
	}
	resp := &pb.GetTopProjectResponse{
		List: make([]*pb.GetTopProjectData, 0),
	}
	if getTopProjectResponse != nil && getTopProjectResponse.Total > 0 {
		for _, v := range getTopProjectResponse.List {
			resp.List = append(resp.List, &pb.GetTopProjectData{
				TopProjectId: v.TopProjectId,
				PrjName:      v.PrjName,
				NodeType:     v.NodeType,
			})
		}
		resp.Total = getTopProjectResponse.Total
	}
	return resp, nil
}

func (s *projectService) GetExportProjectTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.SearchProjectRequest
	switch condition.(type) {
	case *pb.SearchProjectRequest:
		request = condition.(*pb.SearchProjectRequest)
	case string:
		request = &pb.SearchProjectRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "找客户获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.GetProjectListRequest{
		Page:                   1,
		PageSize:               1,
		Keyword:                request.Keyword,
		OrganizingCode:         strings.Join(organizingCodeArr, ","),
		CompanyAreaCode:        strings.Join(request.CompanyAreaCode, ","),
		LandUsage:              strings.Join(request.LandUsage, ","),
		ProjectType:            strings.Join(request.ProjectType, ","),
		FitmentFee:             strings.Join(request.FitmentFee, ","),
		CompanyType:            strings.Join(request.CompanyType, ","),
		CompanyLabel:           strings.Join(request.CompanyLabel, ","),
		IndustryCategory:       strings.Join(request.IndustryCategory, ","),
		ProjectPriceGtAvgLabel: strings.Join(request.ProjectPriceGtAvgLabel, ","),
		TakeLandDateStart:      request.TakeLandDateStart,
		TakeLandDateEnd:        request.TakeLandDateEnd,
		ProjectDateStart:       request.ProjectDateStart,
		ProjectDateEnd:         request.ProjectDateEnd,
		BuildingDateStart:      request.BuildingDateStart,
		BuildingDateEnd:        request.BuildingDateEnd,
		OpenDateStart:          request.OpenDateStart,
		OpenDateEnd:            request.OpenDateEnd,
		CompletedDateStart:     request.CompletedDateStart,
		CompletedDateEnd:       request.CompletedDateEnd,
	}
	//区域
	request.AreaCode, _ = s.filterAreaCode(ctx, request.AreaCode)
	openSearchRequest.AreaCode = strings.Join(request.AreaCode, ",")

	searchData, err := s.openSearchRepos.GetProjectList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetExportProjectTotal GetProjectList request:%#v, err:%s", openSearchRequest, err.Error())
		return
	}

	if searchData == nil {
		return
	}

	total = int64(searchData.Total)
	return
}

func (s *projectService) QueryExportProjectBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeProjectExportFields, "，")
	var request *pb.SearchProjectRequest
	switch condition.(type) {
	case *pb.SearchProjectRequest:
		request = condition.(*pb.SearchProjectRequest)
	case string:
		request = &pb.SearchProjectRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "找客户获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.GetProjectListRequest{
		Page:                   batchNum,
		PageSize:               batchSize,
		Keyword:                request.Keyword,
		OrganizingCode:         strings.Join(organizingCodeArr, ","),
		CompanyAreaCode:        strings.Join(request.CompanyAreaCode, ","),
		LandUsage:              strings.Join(request.LandUsage, ","),
		ProjectType:            strings.Join(request.ProjectType, ","),
		FitmentFee:             strings.Join(request.FitmentFee, ","),
		CompanyType:            strings.Join(request.CompanyType, ","),
		CompanyLabel:           strings.Join(request.CompanyLabel, ","),
		IndustryCategory:       strings.Join(request.IndustryCategory, ","),
		ProjectPriceGtAvgLabel: strings.Join(request.ProjectPriceGtAvgLabel, ","),
		TakeLandDateStart:      request.TakeLandDateStart,
		TakeLandDateEnd:        request.TakeLandDateEnd,
		ProjectDateStart:       request.ProjectDateStart,
		ProjectDateEnd:         request.ProjectDateEnd,
		BuildingDateStart:      request.BuildingDateStart,
		BuildingDateEnd:        request.BuildingDateEnd,
		OpenDateStart:          request.OpenDateStart,
		OpenDateEnd:            request.OpenDateEnd,
		CompletedDateStart:     request.CompletedDateStart,
		CompletedDateEnd:       request.CompletedDateEnd,
	}
	//区域
	request.AreaCode, _ = s.filterAreaCode(ctx, request.AreaCode)
	openSearchRequest.AreaCode = strings.Join(request.AreaCode, ",")
	searchData, err := s.openSearchRepos.GetProjectList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "QueryExportProjectBatchData GetProjectList request:%#v, err:%s", openSearchRequest, err.Error())
		return
	}

	if searchData == nil {
		return
	}

	//项目名称，甲方单位，土地名称，在建项目名称，项目类型，楼盘名称，项目地区，拿地时间，土地用途，立项时间，开工时间，开盘时间，竣工时间，装修状态，销售价格
	for _, item := range searchData.List {
		// 最新土地名称、在建项目名称、楼盘名称
		var latestLandTitle, latestBuildingTitle, latestOpeningTitle string
		// 最新土地拿地时间、立项时间、开工时间、开盘时间、竣工时间
		var latestLandDate, latestApprovalDate, latestBuildingDate, latestOpeningDate, latestCompletionDate string
		for _, landInfo := range item.LandInfoArr {
			if landInfo.TakeLandDate > latestLandDate {
				latestLandDate = landInfo.TakeLandDate
				latestLandTitle = landInfo.Title
			}
		}
		for _, buildInfo := range item.BuildingInfoArr {
			if buildInfo.BuildingDate > latestBuildingDate {
				latestBuildingDate = buildInfo.BuildingDate
				latestBuildingTitle = buildInfo.Title
			}
		}
		for _, openInfo := range item.OpeningInfoArr {
			if openInfo.OpeningDate > latestOpeningDate {
				latestOpeningDate = openInfo.OpeningDate
				latestOpeningTitle = openInfo.Title
			}
		}
		for _, compInfo := range item.CompletionInfoArr {
			if compInfo.CompletedDate > latestCompletionDate {
				latestCompletionDate = compInfo.CompletedDate
			}
		}
		for _, approval := range item.ApprovalInfoArr {
			if approval.ProjectDate > latestApprovalDate {
				latestApprovalDate = approval.ProjectDate
			}
		}

		projectType := ""
		for _, labelData := range item.ProjectTypeLabelArr {
			if projectType != "" {
				projectType += "，"
			}
			projectType += labelData.Label
		}

		landUsage := ""
		for _, labelData := range item.LandUsageLabelArr {
			if landUsage != "" {
				landUsage += "，"
			}
			landUsage += labelData.Label
		}
		feeLabel := ""
		for _, feeData := range item.FitmentFeeLabelArr {
			if feeLabel != "" {
				feeLabel += "，"
			}
			feeLabel += feeData.Label
		}

		addr := fmt.Sprintf("%s%s", item.Province, item.City)
		if item.Province == item.City {
			addr = item.Province
		}

		rowData = append(rowData, []string{
			item.Title,                            //项目名称，
			item.DeveloperName,                    //甲方单位，
			latestLandTitle,                       //土地名称，
			latestBuildingTitle,                   //在建项目名称，
			projectType,                           //项目类型，
			latestOpeningTitle,                    //楼盘名称，
			addr,                                  //项目地区，
			strings.Split(latestLandDate, " ")[0], //拿地时间，
			strings.Split(landUsage, " ")[0],      //土地用途，
			strings.Split(latestApprovalDate, " ")[0],   //立项时间，
			strings.Split(latestBuildingDate, " ")[0],   //开工时间，
			strings.Split(latestOpeningDate, " ")[0],    //开盘时间，
			strings.Split(latestCompletionDate, " ")[0], //竣工时间，
			feeLabel, //装修状态，
		})
	}
	return
}

func (s *projectService) GetExportSaleTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.SaleListRequest
	switch condition.(type) {
	case *pb.SaleListRequest:
		request = condition.(*pb.SaleListRequest)
	case string:
		request = &pb.SaleListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "找客户获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	var newIsPriceGtAvg []string
	for _, v := range request.IsPriceGtAvg {
		if v == "高端项目" {
			v = "是"
		} else {
			v = "否"
		}
		newIsPriceGtAvg = append(newIsPriceGtAvg, v)
	}
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.SaleListRequest{
		PageSize:              1,
		Page:                  1,
		Keyword:               request.Keyword,
		CompanyArea:           strings.Join(request.CompanyArea, ","),
		CompanyType:           strings.Join(request.CompanyType, ","),
		IsPriceGtAvg:          strings.Join(newIsPriceGtAvg, ","),
		FitmentFeeLabel:       strings.Join(request.FitmentFeeLabel, ","),
		PropertyCategoryLabel: strings.Join(request.PropertyCategoryLabel, ","),
		Area:                  strings.Join(request.Area, ","),
		OpeningTimeStart:      request.OpeningTimeStart,
		OpeningTimeEnd:        request.OpeningTimeEnd,
		DeliveryTimeStart:     request.DeliveryTimeStart,
		DeliveryTimeEnd:       request.DeliveryTimeEnd,
		OrganizingCode:        strings.Join(organizingCodeArr, ","),
	}
	for _, v := range request.CompanyLabel {
		if v == constants.CompanyLabelDeveloperTop100Label {
			openSearchRequest.DeveloperTop100Label = v
		} else if v == constants.CompanyLabelNewDecorateExpandLabel {
			openSearchRequest.NewDecorateExpandLabel = v
		} else if v == constants.CompanyLabelNewLandUsageExpandLabel {
			openSearchRequest.NewLandUsageExpandLabel = v
		} else if v == constants.CompanyLabelNewAreaExpandLabel {
			openSearchRequest.NewAreaExpandLabel = v
		} else if v == constants.CompanyLabelPriceGtAvgLabel {
			openSearchRequest.PriceGtAvgLabel = v
		} else if v == constants.CompanyLabelUrbanInvestmentLabel {
			openSearchRequest.UrbanInvestmentLabel = v
		}
	}
	searchData, err := s.openSearchRepos.SaleList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetExportSaleTotal SaleList request:%#v, err:%s", openSearchRequest, err.Error())
		return
	}

	if searchData == nil {
		return
	}

	total = int64(searchData.Total)
	return
}

func (s *projectService) QueryExportSaleBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeSaleExportFields, "，")
	var request *pb.SaleListRequest
	switch condition.(type) {
	case *pb.SaleListRequest:
		request = condition.(*pb.SaleListRequest)
	case string:
		request = &pb.SaleListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "获取开盘导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	var newIsPriceGtAvg []string
	for _, v := range request.IsPriceGtAvg {
		if v == "高端项目" {
			v = "是"
		} else {
			v = "否"
		}
		newIsPriceGtAvg = append(newIsPriceGtAvg, v)
	}
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.SaleListRequest{
		PageSize:              batchSize,
		Page:                  batchNum,
		Keyword:               request.Keyword,
		CompanyArea:           strings.Join(request.CompanyArea, ","),
		CompanyType:           strings.Join(request.CompanyType, ","),
		IsPriceGtAvg:          strings.Join(newIsPriceGtAvg, ","),
		FitmentFeeLabel:       strings.Join(request.FitmentFeeLabel, ","),
		PropertyCategoryLabel: strings.Join(request.PropertyCategoryLabel, ","),
		Area:                  strings.Join(request.Area, ","),
		OpeningTimeStart:      request.OpeningTimeStart,
		OpeningTimeEnd:        request.OpeningTimeEnd,
		DeliveryTimeStart:     request.DeliveryTimeStart,
		DeliveryTimeEnd:       request.DeliveryTimeEnd,
		OrganizingCode:        strings.Join(organizingCodeArr, ","),
	}
	for _, v := range request.CompanyLabel {
		if v == constants.CompanyLabelDeveloperTop100Label {
			openSearchRequest.DeveloperTop100Label = v
		} else if v == constants.CompanyLabelNewDecorateExpandLabel {
			openSearchRequest.NewDecorateExpandLabel = v
		} else if v == constants.CompanyLabelNewLandUsageExpandLabel {
			openSearchRequest.NewLandUsageExpandLabel = v
		} else if v == constants.CompanyLabelNewAreaExpandLabel {
			openSearchRequest.NewAreaExpandLabel = v
		} else if v == constants.CompanyLabelPriceGtAvgLabel {
			openSearchRequest.PriceGtAvgLabel = v
		} else if v == constants.CompanyLabelUrbanInvestmentLabel {
			openSearchRequest.UrbanInvestmentLabel = v
		}
	}
	saleResponse, err := s.openSearchRepos.SaleList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "opensearch SaleList,err:%s", err.Error())
	}

	if saleResponse == nil || saleResponse.Total == 0 {
		return
	}

	//项目名称，项目地区，项目类型，装修类型，建设单位，开盘时间，交房时间
	for _, item := range saleResponse.List {
		area := ""
		if item.Province == item.City {
			area = item.Province
		} else {
			area = fmt.Sprintf("%s%s", item.Province, item.City)
		}
		rowData = append(rowData, []string{
			item.ProjectTitle,                        //项目名称，
			area,                                     //项目地区，
			item.PropertyCategoryLabel,               //项目类型，
			item.FitmentFeeLabel,                     //装修类型，
			item.DeveloperName,                       //建设单位，
			strings.Split(item.OpeningTime, " ")[0],  //开盘时间，
			strings.Split(item.DeliveryTime, " ")[0], //交房时间
		})
	}

	return
}

// GetTakenLand 拿地列表
func (s *projectService) GetTakenLand(ctx context.Context, request *pb.GetTakeLandListRequest) (*pb.GetTakeLandListResponse, error) {
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.TakeLandListRequest{
		Keyword:           request.Keyword,
		OrganizingCode:    strings.Join(organizingCodeArr, ","),
		Area:              strings.Join(request.AreaCode, ","),
		TakeLandDateStart: request.TakeLandDateStart,
		TakeLandDateEnd:   request.TakeLandDateEnd,
		LandType:          strings.Join(request.LandUsage, ","),
		Page:              request.Page,
		PageSize:          request.PageSize,
		LandPriceLower:    request.LandPriceMin,
		LandPriceUpper:    request.LandPriceMax,
		AreaLower:         request.LandAreaMin,
		AreaUpper:         request.LandAreaMax,
		IsPriceGtAvg:      request.IsPriceGtAvg,
		CompanyArea:       strings.Join(request.CompanyAreaCode, ","),
		CompanyType:       strings.Join(request.CompanyType, ","),
	}
	for _, label := range request.CompanyLabel {
		switch label {
		case "地产百强":
			openSearchRequest.DeveloperTop100Label = label
		case "新精装客群":
			openSearchRequest.NewDecorateExpandLabel = label
		case "新住宅客群":
			openSearchRequest.NewLandUsageExpandLabel = label
		case "新区域拓展":
			openSearchRequest.NewAreaExpandLabel = label
		case "高端项目客群":
			openSearchRequest.PriceGtAvgLabel = label
		case "城投企业":
			openSearchRequest.UrbanInvestmentLabel = label
		}
	}

	openSearchData, err := s.openSearchRepos.TakeLandList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTakenLand TakeLandList request:%#v, err:%s", openSearchRequest, err.Error())
		return nil, err
	}
	result := &pb.GetTakeLandListResponse{}
	if openSearchData == nil {
		return result, nil
	}
	result.Total = openSearchData.Total
	for _, item := range openSearchData.List {
		pbItem := &pb.TakeLandItem{
			OrganizingCode:     item.OrganizingCode,
			DeveloperName:      item.DeveloperName,
			DeveloperNameHl:    item.DeveloperNameHl,
			SubOrganizingCode:  item.OrganizingCode,
			SubDeveloperName:   item.DeveloperName,
			Level:              item.LandLevel,
			InfoType:           item.InfoType,
			LandTitle:          item.LandTitle,
			LandTitleHl:        item.LandTitleHl,
			ProjectName:        item.ProjectName,
			TakeLandDate:       strings.Split(item.TakeLandDate, " ")[0], //只取到年月日
			IssueDate:          strings.Split(item.IssueDate, " ")[0],    //只取到年月日
			PlannedArea:        item.PlannedArea,
			AllArea:            fmt.Sprintf("%.2f", item.AllArea),
			LandUsage:          item.LandUsage,
			Province:           item.Province,
			ProvinceCode:       item.ProvinceCode,
			City:               item.City,
			CityCode:           item.CityCode,
			LandAddress:        item.LandAddress,
			TakeLandPrice:      fmt.Sprintf("%.2f", item.TakeLandPrice),
			LandLevel:          item.LandLevel,
			TradeType:          item.TradeType,
			UseTimeDescription: item.UseTimeDescription,
			Authority:          item.Authority,
			LandSource:         item.LandSource,
			Industry:           item.Industry,
			Region:             item.Region,
			Id:                 item.Id,
			CreatedAt:          strings.Split(item.CreatedAt, " ")[0], //只取到年月日,
			UpdatedAt:          strings.Split(item.UpdatedAt, " ")[0],
		}
		if item.IsPriceGtAvg == "是" {
			pbItem.PriceGtAvgLabel = "高端项目"
		}
		var landUsageLabels []string
		for _, labelData := range item.LandUsageLabel {
			landUsageLabels = append(landUsageLabels, labelData.Label)
			pbItem.LandUsageLabel = strings.Join(landUsageLabels, ",")
		}

		result.List = append(result.List, pbItem)
	}

	return result, nil
}

// GetExportTakenLandTotal  导出客户详情-拿地列表获取总记录数
func (s *projectService) GetExportTakenLandTotal(ctx context.Context, condition interface{}) (total int64, err error) {
	var request *pb.GetTakeLandListRequest
	switch condition.(type) {
	case *pb.GetTakeLandListRequest:
		request = condition.(*pb.GetTakeLandListRequest)
	case string:
		request = &pb.GetTakeLandListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情-拿地列表获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}
	// 获取总条目，只需要取一条数据就好了
	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.TakeLandListRequest{
		Keyword:           request.Keyword,
		OrganizingCode:    strings.Join(organizingCodeArr, ","),
		Area:              strings.Join(request.AreaCode, ","),
		TakeLandDateStart: request.TakeLandDateStart,
		TakeLandDateEnd:   request.TakeLandDateEnd,
		LandType:          strings.Join(request.LandUsage, ","),
		Page:              1,
		PageSize:          1,
		LandPriceLower:    request.LandPriceMin,
		LandPriceUpper:    request.LandPriceMax,
		AreaLower:         request.LandAreaMin,
		AreaUpper:         request.LandAreaMax,
		IsPriceGtAvg:      request.IsPriceGtAvg,
		CompanyArea:       strings.Join(request.CompanyAreaCode, ","),
		CompanyType:       strings.Join(request.CompanyType, ","),
	}
	for _, label := range request.CompanyLabel {
		switch label {
		case "地产百强":
			openSearchRequest.DeveloperTop100Label = label
		case "新精装客群":
			openSearchRequest.NewDecorateExpandLabel = label
		case "新住宅客群":
			openSearchRequest.NewLandUsageExpandLabel = label
		case "新区域拓展":
			openSearchRequest.NewAreaExpandLabel = label
		case "高端项目客群":
			openSearchRequest.PriceGtAvgLabel = label
		case "城投企业":
			openSearchRequest.UrbanInvestmentLabel = label
		}
	}
	openSearchData, err := s.openSearchRepos.TakeLandList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetExportTakenLandTotal TakeLandList request:%#v, err:%s", openSearchRequest, err.Error())
		return 0, err
	}
	if openSearchData == nil {
		return
	}

	total = int64(openSearchData.Total)
	return
}

// QueryExportTakenLandBatchData 导出客户详情-拿地列表，分批获取数据
func (s *projectService) QueryExportTakenLandBatchData(ctx context.Context, condition interface{}, batchNum, batchSize int32) (rowTitle []string, rowData [][]string, err error) {
	rowTitle = strings.Split(constants.OrderTypeCustomerDetailLandExportFields, "，")
	var request *pb.GetTakeLandListRequest
	switch condition.(type) {
	case *pb.GetTakeLandListRequest:
		request = condition.(*pb.GetTakeLandListRequest)
	case string:
		request = &pb.GetTakeLandListRequest{}
		if condition.(string) != "" {
			err = json.Unmarshal([]byte(condition.(string)), request)
			if err != nil {
				stark.Logger.Errorf(ctx, "客户详情-拿地列表获取导出记录条数错误,condition:%+v, err:%s", condition, err)
				return
			}
		}
	}

	var organizingCodeArr []string
	if request.OrganizingCode != "" {
		organizingCodeArr, _ = s.bigDataServiceRepo.GetInvestCompanyCodes(ctx, request.OrganizingCode)
	}
	openSearchRequest := &opensearch_remote.TakeLandListRequest{
		Keyword:           request.Keyword,
		OrganizingCode:    strings.Join(organizingCodeArr, ","),
		Area:              strings.Join(request.AreaCode, ","),
		TakeLandDateStart: request.TakeLandDateStart,
		TakeLandDateEnd:   request.TakeLandDateEnd,
		LandType:          strings.Join(request.LandUsage, ","),
		Page:              batchNum,
		PageSize:          batchSize,
		LandPriceLower:    request.LandPriceMin,
		LandPriceUpper:    request.LandPriceMax,
		AreaLower:         request.LandAreaMin,
		AreaUpper:         request.LandAreaMax,
		IsPriceGtAvg:      request.IsPriceGtAvg,
		CompanyArea:       strings.Join(request.CompanyAreaCode, ","),
		CompanyType:       strings.Join(request.CompanyType, ","),
	}
	for _, label := range request.CompanyLabel {
		switch label {
		case "地产百强":
			openSearchRequest.DeveloperTop100Label = label
		case "新精装客群":
			openSearchRequest.NewDecorateExpandLabel = label
		case "新住宅客群":
			openSearchRequest.NewLandUsageExpandLabel = label
		case "新区域拓展":
			openSearchRequest.NewAreaExpandLabel = label
		case "高端项目客群":
			openSearchRequest.PriceGtAvgLabel = label
		case "城投企业":
			openSearchRequest.UrbanInvestmentLabel = label
		}
	}
	openSearchData, err := s.openSearchRepos.TakeLandList(ctx, openSearchRequest)
	if err != nil {
		stark.Logger.Errorf(ctx, "QueryExportTakenLandBatchData TakeLandList request:%#v, err:%s", openSearchRequest, err.Error())
		return nil, nil, err
	}
	if openSearchData == nil {
		return
	}

	for _, item := range openSearchData.List {
		area := ""
		if item.Province == item.City {
			area = item.Province
		} else {
			area = fmt.Sprintf("%s%s", item.Province, item.City)
		}
		var landUsageLabels []string
		for _, labelData := range item.LandUsageLabel {
			landUsageLabels = append(landUsageLabels, labelData.Label)
		}
		rowData = append(rowData, []string{
			item.LandTitle,                     //土地名称，
			strings.Join(landUsageLabels, ","), //土地用途，
			area,                               //所在地区，
			item.TakeLandDate,                  //拿地时间，
			fmt.Sprintf("%.2f万人民币", item.TakeLandPrice), //成交价格，
			fmt.Sprintf("%.2f平米", item.AllArea),         //占地面积，
			item.DeveloperName,                          //拿地单位，
			item.TopDeveloperName,                       //顶级公司
		})
	}

	return
}
